package com.youhome.service.service.impl;

import com.github.pagehelper.PageHelper;
import com.youhome.service.mapper.ZipMapper;
import com.youhome.service.model.Zip;
import com.youhome.service.model.AssociateCity;
import com.youhome.service.model.AssociateZip;
import com.youhome.service.service.ZipService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chen365 on 2017/10/31.
 */
@Service
public class ZipServiceImpl implements ZipService {
    @Autowired
    private ZipMapper zipMapper;

    @Override
    public List<String> selectByCity(String city) throws Exception {
        return zipMapper.selectZipsByCity(city);
    }

    @Override
    public List<Zip> selectByLikeZipCode(String zipCode, int page, int pageSize) {
        PageHelper.startPage(page, pageSize);
        List<Zip> list = zipMapper.selectByLikeZipCode(zipCode);
        return list;
    }

    @Override
    public List<Zip> selectByLikeCity(String city, int page, int pageSize) {
        PageHelper.startPage(page, pageSize);
        List<Zip> list = zipMapper.selectByLikeCity(city);
        return list;
    }

    @Override
    public List<AssociateZip> selectAssociateByLikeZip(String zip) {
        return zipMapper.selectAssociateByLikeZip(zip);
    }

    @Override
    public List<AssociateCity> selectAssociateByLikeCity(String city) {
        return zipMapper.selectAssociateByLikeCity(city);
    }

    @Override
    public Zip selectByPrimaryKey(String zipcode) {
        return zipMapper.selectByPrimaryKey(zipcode);
    }

    @Override
    public List<String> selectZipsByCity(String city) {
        return zipMapper.selectZipsByCity(city);
    }

    @Override
    public List<Zip> selectByBean(Zip record) {
        return zipMapper.selectByBean(record);
    }

    /**
     * 查询与 zipcode 相同城市下所有 zipcode 数据,不包含查询的zipcode
     *
     * @param zip 邮编
     * @return
     */
    @Override
    public List<String> selectSameCityZipsByZip(String zip) {
        List<String> list = zipMapper.selectSameCityZipsByZip(zip);
        return getStandardZip(list);
    }

    public List<String> getStandardZip(List<String> zips) {
        List<String> standardZip = new ArrayList<>();
        for (String zip : zips) {
            //超过5位的截取前5位
            if (zip.length() > 5) {
                zip = zip.substring(0, 5);
            }
            //不够5位的舍去
            if (zip != null && zip.length() == 5) {
                standardZip.add(zip);
            }
        }
        return standardZip;
    }
}
